package com.example.toolsdemo.service.impl;

import com.example.toolsdemo.common.ServerResponse;
import com.example.toolsdemo.dataobject.Student;
import com.example.toolsdemo.mapper.StudentMapper;
import com.example.toolsdemo.service.StudentService;
import com.example.toolsdemo.utils.PagedGridResult;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * @author danyubin
 */
@Service
public class StudentServiceImpl implements StudentService {

    @Autowired
    private StudentMapper studentMapper;

    @Override
    public Student getStudent(Long id) {
        return studentMapper.selectByPrimaryKey(id);
    }

    @Override
    public Integer saveStudent(Student student) {
        student.setCreateTime(new Date());
        student.setUpdateTime(new Date());
        return studentMapper.insert(student);
    }

    @Override
    public ServerResponse modifyStudent(Student student) {

        if (student.getId() == null) {
            return ServerResponse.error("学生id不能为空");
        }

        int updateResult = studentMapper.updateByPrimaryKeySelective(student);
        if (updateResult > 0) {
            return ServerResponse.success("更新成功");
        }
        return ServerResponse.error("更新失败");
    }

    @Override
    public Integer deleteStudent(Long id) {
        return studentMapper.deleteByPrimaryKey(id);
    }

    @Override
    public ServerResponse getStudentsByStatus(Integer status, Integer pageNum, Integer pageSize) {

        PageHelper.startPage(pageNum,pageSize);
        List<Student> studentList = studentMapper.findAllByStatus(status);
        PagedGridResult pagedGridResult = setterPagedGrid(studentList, pageNum);
        return ServerResponse.success(pagedGridResult);
    }

    private PagedGridResult setterPagedGrid(List<?> list, Integer page) {
        PageInfo<?> pageList = new PageInfo<>(list);
        PagedGridResult grid = new PagedGridResult();
        grid.setPage(page);
        grid.setRows(list);
        grid.setTotal(pageList.getPages());
        grid.setRecords(pageList.getTotal());
        return grid;
    }
}
